import hashlib

from apps.blueprints.goods.models import Goods, User_Goods
from apps.blueprints.user.models import User
from exts import db
from flask import flash, redirect, render_template, request, session, url_for
from flask_login import login_required, login_user, logout_user
from sqlalchemy import and_, not_, or_

from . import goods_bp


@goods_bp.route('/findgoods') # 根据用户找商品
def find_goods():
    user_id = request.args.get('uid')
    user = User.query.get(user_id) # 根据用户id找用户
    return render_template('goods/findgoods.html',user=user)


@goods_bp.route('/finduser') # 根据商品找用户
def find_user():
    goods_id = request.args.get('gid')
    
    goods = Goods.query.get(goods_id) # 根据商品id找商品
    return render_template('goods/finduser.html', goods=goods)
    return '成功'

@goods_bp.route('/show') # 根用户购买商品
def show():
    users = User.query.filter(User.isdelete==False).all()
    goods = Goods.query.all()
    return render_template('goods/show.html', 
                           users=users,
                           goods_list=goods)
@goods_bp.route('/buy') # 购买商品后，写入user_goods表
def buy():
    uid = request.args.get('uid')
    gid = request.args.get('gid')
    
    ug = User_Goods(user_id=uid, goods_id=gid)
    db.session.add(ug)
    db.session.commit() # 把用户id和goods_id写入user_goods表
    
    user = User.query.get(uid) # 根据用户id找用户
    goods = Goods.query.get(gid) # 根据商品id找商品   
    
    return f"<h2>< {user.username} >购买< {goods.gname} >成功</h2>"
